from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.api import channel
from common import BaseRequestHandler
import logging
import common

class Observable():
    def __init__(self, room):
        self._room = room
        self._observers = memcache.get(self._room)

    def add_observer(self, user):
        if self._observers is not None:
            self._observers.update(user)
        else:
            self._observers = user

        if not memcache.set(self._room, self._observers, 30*60):
            logging.error("Memcache set failed.")

    def delete_observer(self, user):
        del self._observers[user]
    def notify_observers(self, data):
        for channel_id in self._observers.values():
            channel.send_message(channel_id, data)

class Observer(BaseRequestHandler):
    def __init__( self):
        channel_name = common.get_channel_name(users.get_current_user().user_id())
        self.observable = Observable(channel_name)
        
    def update(self, arg):
        self.observable.notify_observers(arg)